package com.yueshop.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//feign远程调用配置,解决远程调用丢失请求头的问题
@Configuration
public class YueshopFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                System.out.println("拦截器.."+Thread.currentThread().getId());
                //1.获取当前请求头数据
                ServletRequestAttributes requestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(requestAttributes!=null){
                    HttpServletRequest request = requestAttributes.getRequest();
                    if(request!=null){
                        //1.获取旧的请求请求头数据
                        String cookie = request.getHeader("Cookie");
                        //2.给心情求同步旧cookie数据
                        template.header("Cookie",cookie);
                    }

                }
            }
        };
    }
}
